import React, {Component} from "react";
import ShowList from './ShowList'
import {selectItemData} from "./action";
import connect from "react-redux/es/connect/connect";
import {Pagination} from 'antd';
import {PAGE, PAGE_SIZE} from "../config/ConfigPage";

class PageList extends Component {
    constructor(props) {
        super(props);
        this.state = {
            page: PAGE,
            pageSize: PAGE_SIZE,
            pageData: [],
        };
    }

    onItemClick(item, i) {
        this.props.selectItemData(item);
    }

    componentWillMount() {
        const {page, pageSize} = this.state;
        this.setState({
            pageData: this.returnPageData(page, pageSize)
        })
    }

    returnPageData(page, pageSize) {
        let newPageData = [];
        let oldData = this.props.result;
        let length = oldData.length - ((page - PAGE) * pageSize);
        let size = pageSize * (page - PAGE);

        if (length < pageSize) {
            for (let i = size; i < oldData.length; i++) {
                newPageData.push(oldData[i]);
            }
        } else {
            for (let i = size; i < (page * pageSize); i++) {
                newPageData.push(oldData[i]);
            }
        }
        return newPageData;
    }


    pageChange(page, pageSize) {

        this.setState({
            pageData: this.returnPageData(page, pageSize),
            page: page
        });
    }


    render() {
        return <div>
            <ShowList onItemClick={this.onItemClick.bind(this)}
                      result={this.state.pageData}/>
            <Pagination
                current={this.state.page}
                total={this.props.result.length}
                onChange={this.pageChange.bind(this)}
                pageSize={this.state.pageSize}/>
        </div>
    }
}

const mapStateToProps = state => {
    return {
        result: state.result
    };
};

const mapDispatchToProps = dispatch => {
    return {
        selectItemData: (selectData) => {
            dispatch(selectItemData(selectData));
        }
    };
};

PageList = connect(
    mapStateToProps,
    mapDispatchToProps
)(PageList);
export default PageList;
